package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.common.constant.TableConsts;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.loader.IInstLoader;
import com.iwhalecloud.bss.kite.cucc.order.loader.InstLoaderFactory;
import com.iwhalecloud.bss.kite.cucc.order.loader.impl.ProdInstLoader;
import com.iwhalecloud.bss.kite.cucc.order.util.AcceptUtils;
import com.iwhalecloud.bss.kite.dataservice.entity.inst.OfferInst;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.order.client.dto.InstContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.iwhalecloud.bss.kite.order.client.proxy.InstContainerProxy;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 可选包销售品实例处理
 */
@Component
public class AdditionalOfferInstHandler extends AbstractOrderHandler {

    @Override
    public void doHandle(OrderRequest orderRequest) {
        /*
         * 可选包销售品实例不生成订单项，如果可选包销售品实例的actionType不是K，还要把上级销售品实例拉出来把actionType改为M生成订单项
         * 例如：给可选包订购一个在用号码，只有一条明细关系实例的变动信息，此时InstContainer里只一个可选包的OfferInst和OfferObjInstRel，
         *       由于可选包不会生成订单项，还要把可选包的上级销售品(套餐、促销、基础销售品)拉出来，actionType改M才能生成相应的订单项
         */
        InstContainerProxy instContainer = InstContainer.ofRequest(orderRequest);
        IInstLoader<OfferInst> instLoader = InstLoaderFactory.getInstLoader(TableConsts.OfferInst.getTableName());
        ProdInstLoader prodInstLoader = InstLoaderFactory.getInstLoader(TableConsts.ProdInst.getTableName());
        List<OfferInst> offerInsts = instContainer.listOfferInsts();
        for (OfferInst offerInst : offerInsts) {
            if (!Objects.equals(CoreDataOffer.OFF_0005_12, offerInst.getOfferType())
                || Objects.equals(ActionType.K.name(), AcceptUtils.getActionType(offerInst))) {
                continue;
            }

            OfferInst parentOfferInst = instLoader.loadInst(orderRequest, TableConsts.OfferInst.getTableName(),
                offerInst.getCompInstId(), offerInst.getOwnerCustId());
            if (Objects.equals(ActionType.K.name(), AcceptUtils.getActionType(parentOfferInst))) {
                AcceptUtils.setActionType(parentOfferInst, ActionType.M.name());
            }

            // 如果可选包销售品实例的上级是基础销售品实例，还要加载相应的接入产品实例
            if (Objects.equals(CoreDataOffer.OFF_0005_10, parentOfferInst.getOfferType())) {
                prodInstLoader.loadInstByCompInstId(orderRequest, parentOfferInst.getOfferInstId(),
                    parentOfferInst.getOwnerCustId());
            }
        }
    }
}
